package org.blogwu.learn.multithread.chapter3.demo5;

import java.time.LocalDate;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class Main extends Thread {
    // 一次允许5个线程进入临界区
    static Semaphore semaphore = new Semaphore(5);

    public Main(String name) {
        super(name);
    }

    @Override
    public void run() {
        try {
            // 获取一个进入临界区的凭证
            semaphore.acquire();
            Thread.sleep(3000);
            System.out.println(getName() + " exec time:" + LocalDate.now());
            ;
            semaphore.release(); // 释放一个进入临界区的凭证
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        for (int i = 0; i < 20; i++) {
            executorService.submit(new Main("t" + i));
        }

    }
}
